package cn.iocoder.yudao.module.design.controller.admin.house;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum;
import cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.framework.security.core.LoginUser;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.design.controller.admin.flow.vo.FlowCreatePurcharseReqVO;
import cn.iocoder.yudao.module.design.controller.admin.house.vo.*;
import cn.iocoder.yudao.module.design.controller.admin.house.vo.simpleVo.HouseSimpleRespVO;
import cn.iocoder.yudao.module.design.controller.admin.houseUserRel.vo.HouseUserRelCreateReqVO;
import cn.iocoder.yudao.module.design.convert.house.HouseConvert;
import cn.iocoder.yudao.module.design.dal.dataobject.flow.FlowCountDO;
import cn.iocoder.yudao.module.design.dal.dataobject.flowtask.FlowTaskCountDO;
import cn.iocoder.yudao.module.design.dal.dataobject.house.HouseDO;
import cn.iocoder.yudao.module.design.dal.dataobject.houseUserRel.HouseUserRelDO;
import cn.iocoder.yudao.module.design.dal.dataobject.pic.PicDO;
import cn.iocoder.yudao.module.design.dal.dataobject.problem.ProblemCountDO;
import cn.iocoder.yudao.module.design.enums.design.FlowTaskStatusEnum;
import cn.iocoder.yudao.module.design.enums.design.PicSourceTypeEnum;
import cn.iocoder.yudao.module.design.enums.design.UserRelStatusCdEnum;
import cn.iocoder.yudao.module.design.service.flow.FlowService;
import cn.iocoder.yudao.module.design.service.flowtask.FlowTaskService;
import cn.iocoder.yudao.module.design.service.house.HouseService;
import cn.iocoder.yudao.module.design.service.houseUserRel.HouseUserRelService;
import cn.iocoder.yudao.module.design.service.problem.ProblemService;
import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.yudao.module.design.enums.ErrorCodeConstants;
import cn.iocoder.yudao.module.system.service.user.AdminUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertList;

@Tag(name = "管理后台 - 设计项目")
@RestController
@RequestMapping("/design/house")
@Validated
public class HouseController {

    @Resource
    private HouseService houseService;

    @Resource
    private FlowService flowService;

    @Resource
    private HouseUserRelService houseUserRelService;

    @Resource
    private AdminUserService userService;


    @Resource
    @Lazy
    private ProblemService problemService;

    @Resource
    @Lazy
    private FlowTaskService flowTaskService;




    @PostMapping("/create")
    @Operation(summary ="创建项目")
    @PreAuthorize("@ss.hasPermission('design:house:create')")
    public CommonResult<Long> createHouse(@Valid @RequestBody HouseCreateReqVO createReqVO) {
        return success(houseService.createHouse(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary ="更新项目")
    @PreAuthorize("@ss.hasPermission('design:house:update')")
    public CommonResult<Boolean> updateHouse(@Valid @RequestBody HouseUpdateReqVO updateReqVO) {
        houseService.updateHouse(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary ="删除项目")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('design:house:delete')")
    public CommonResult<Boolean> deleteHouse(@RequestParam("id") Long id) {
        houseService.deleteHouse(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary ="获得项目")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('design:house:query')")
    public CommonResult<HouseRespVO> getHouse(@RequestParam("id") Long id) {

        return success(houseService.getHouseById(id));
    }


    @GetMapping("/list")
    @Operation(summary ="获得项目列表")
    @Parameter(name = "ids", description = "编号列表", required = true, example = "1024,2048")
    @PreAuthorize("@ss.hasPermission('design:house:query')")
    public CommonResult<List<HouseRespVO>> getHouseList(@RequestParam("ids") Collection<Long> ids) {
        List<HouseDO> list = houseService.getHouseList(ids);
        return success(HouseConvert.INSTANCE.convertList(list));
    }
    @GetMapping("/all")
    @Operation(summary ="获得项目列表")
    @PreAuthorize("@ss.hasPermission('design:house:query')")
    @Parameter(name = "HouseBaseVO", description = "HouseBaseVO")
    public CommonResult<List<HouseRespVO>> getHouseAll(@Valid HouseBaseVO pageVO) {
        List<HouseRespVO> list = houseService.getHouseList(pageVO);

        return success(list);
    }
    @GetMapping("/page")
    @Operation(summary ="获得项目分页")
    @PreAuthorize("@ss.hasPermission('design:house:query')")
    public CommonResult<PageResult<HouseRespVO>> getHousePage(@Valid HousePageReqVO pageVO) {
        //  SecurityFrameworkUtils  getLoginUserRoleIds 获取当前用户角色 getLoginUser  获取当前用户  getLoginUserId  用户编号
        /*1.根据userId 查询hd_user_rel 中所有房子id  2. 根据查询的userId 查询房子信息*/
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        HouseUserRelDO houseUserRelDO = new HouseUserRelDO();
        houseUserRelDO.setUserId(loginUser.getId());
        // 正常加入项目的
        houseUserRelDO.setStatus(UserRelStatusCdEnum.USER_REL_STATUS_CD_1.getCode().toString());
        List<HouseUserRelDO> userIds = houseUserRelService.getHouseUserRelList(houseUserRelDO);
        Set<Long> houseIds = userIds.stream().map(userRelDO -> userRelDO.getHouseId()).collect(Collectors.toSet());

        // 平台管理员跳过 权限控制
        if(loginUser.getId()!=1 ) {
            if(CollUtil.isEmpty(houseIds)){
                return success(new PageResult<>(new ArrayList<>(), 0L));
            }else{
                pageVO.setIds(houseIds);
            }
        }



        if(StrUtil.isEmpty(pageVO.getStatus())){
            pageVO.setStatus("1");
        }
         // 我创建的项目
        if("1".equals(pageVO.getOptionType())){
            pageVO.setDesignerId(loginUser.getId());
        }
        PageResult<HouseDO> pageResult = houseService.getHousePage(pageVO);

        // 获得拼接需要的数据
        Set<Long> designerIds = new HashSet<>(convertList(pageResult.getList(), HouseDO::getDesignerId));

        Map<Long, AdminUserDO> userMap = userService.getUserMap(designerIds);
        // 项目id集合
        Set<Long> houseIdList = new HashSet<>(convertList(pageResult.getList(), HouseDO::getId));
        // 查询本人在每个项目的待办数

        // 查询本人在每个项目的待处理问题数
        // 拼接结果返回
        List<HouseRespVO> houseRespVOList = new ArrayList<>(pageResult.getList().size());
        pageResult.getList().forEach(user -> {
            HouseRespVO respVO = HouseConvert.INSTANCE.convert(user);
            respVO.setDesignerName(userMap.get(user.getDesignerId()).getNickname());
            houseRespVOList.add(respVO);

        });

        return success(new PageResult<>(houseRespVOList, pageResult.getTotal()));
    }

    @GetMapping("/export-excel")
    @Operation(summary ="导出项目 Excel")
    @PreAuthorize("@ss.hasPermission('design:house:export')")
   
    public void exportHouseExcel(@Valid HouseExportReqVO exportReqVO,
              HttpServletResponse response) throws IOException {
        List<HouseDO> list = houseService.getHouseList(exportReqVO);
        // 导出 Excel
        List<HouseExcelVO> datas = HouseConvert.INSTANCE.convertList02(list);
        ExcelUtils.write(response, "项目.xls", "数据", HouseExcelVO.class, datas);
    }


    @GetMapping("/list-all-simple")
    @Operation(summary = "获取房子精简信息列表", description = "只包含被开启的房子，主要用于前端的下拉选项")
    @PreAuthorize("@ss.hasPermission('design:house:query')")
    public CommonResult<List<HouseSimpleRespVO>> getSimpleHouse() {
        // 获用户门列表，只要开启状态的
        List<HouseDO> list = houseService.getHouseByStatus(CommonStatusEnum.ENABLE.getStatus());
        // 排序后，返回给前端
        return success(HouseConvert.INSTANCE.convertList04(list));
    }




    @PostMapping("/createUserRel")
    @Operation(summary ="新增项目关联人并注册用户")
    @PreAuthorize("@ss.hasPermission('design:house:createUserRel')")
    public CommonResult<Long> createUserRel(@Valid @RequestBody HouseUserRelVO createReqVO) {
        Long userRel = houseService.createUserRel(createReqVO);
        return success(userRel);
    }

    @GetMapping("/createStyleCd")
    @Operation(summary ="新增项目风格")
    @PreAuthorize("@ss.hasPermission('design:house:create')")
    public CommonResult<Long> createStyleCd(@RequestParam("styleName")  String styleName) {
        return success(houseService.createStyleCd(styleName));
    }

   @GetMapping("/getHouseNodeAndUrl")
    @Operation(summary ="查询装修记录信息")
    @PreAuthorize("@ss.hasPermission('design:house:query')")
    public CommonResult<List<HouseNodeDateVO>> getHouseNodeAndUrl(@RequestParam("houseId") Long houseId) {

        return success(houseService.getHouseNodeAndUrl(houseId));
    }

    @GetMapping("/closeHouse")
    @Operation(summary ="关闭项目")
    @PreAuthorize("@ss.hasPermission('design:house:create')")
    public CommonResult<Boolean> closeHouse(@RequestParam("id") Long houseId) {

        houseService.closeHouse(houseId);
        return success(true);
    }

    @PostMapping("/createPrincipalUserRel")
    @Operation(summary ="新增供应商负责人并注册用户")
    @PreAuthorize("@ss.hasPermission('design:house:createUserRel')")
    public CommonResult<Long> createPrincipalUserRel(@Valid @RequestBody HousePrincipalUserRelVO createReqVO) {
        Long principalUserRel = houseService.createPrincipalUserRel(createReqVO);
  
        return success(principalUserRel);
    }


    @PostMapping("/createPrincipalAdminRel")
    @Operation(summary ="新增供应商并注册用户")
    @PreAuthorize("@ss.hasPermission('design:house:createUserRel')")
    public CommonResult<Long> createPrincipalAdminRel(@Valid @RequestBody HousePrincipalUserRelVO vo) {

        HouseUserRelVO houseUserRelVO = BeanUtil.copyProperties(vo, HouseUserRelVO.class);
        // 创建供应商用户
        Long userId = houseService.createUserRel(houseUserRelVO);
        // 判断供应商是否已在项目中
        List<HouseUserRelDO> userRoleList = houseUserRelService.
                getHouseUserRelByHouseIdAndUserIdAndRoleId(vo.getHouseId(), userId, Long.valueOf(vo.getRoleId()));
        if(userRoleList.size()>0){
            throw ServiceExceptionUtil.exception(ErrorCodeConstants.GYS_USER_ID_EXITS);
        }
        HouseRespVO houseById = houseService.getHouseById(vo.getHouseId());

        //  项目关联任务初始化为待开始 ,  待好友通过后  自动改为进行中
        houseService.saveHouseUserRelTask(vo.getHouseId(),houseById.getProjectName(),userId,
                Long.valueOf(vo.getRoleId()), FlowTaskStatusEnum.FLOW_STATUS_ENUM_2.getCode());

        // 关联好友关系建立
        HouseUserRelCreateReqVO houseUserRel = new HouseUserRelCreateReqVO();
        houseUserRel.setHouseId(houseById.getId());
        houseUserRel.setUserId(userId);
        houseUserRel.setStatus(UserRelStatusCdEnum.USER_REL_STATUS_CD_1.getCode().toString());
        houseUserRel.setRoleId(vo.getRoleId());
        houseUserRelService.createHouseUserRel(houseUserRel);
        // 查询采购流程
        FlowCreatePurcharseReqVO flowCreatePurcharseReqVO = new FlowCreatePurcharseReqVO();
        flowCreatePurcharseReqVO.setHouseId(houseById.getId());
        flowCreatePurcharseReqVO.setDealerId(userId);
        flowCreatePurcharseReqVO.setSupplierId(userId);
        flowCreatePurcharseReqVO.setStartTime(new Date());
        flowService.createPurchaseFlow(flowCreatePurcharseReqVO);


        return success(userId);
    }
    @PostMapping("/addPicData")
    @Operation(summary ="保存项目图片")
    @PreAuthorize("@ss.hasPermission('design:house:create')")
    public CommonResult<Boolean> addPicData(@Valid @RequestBody HouseUpdatePicDataReqVO createReqVO) {
        houseService.addPicData(createReqVO);
        return success(true);
    }


    @GetMapping("/getSimHouseInfo")
    @Operation(summary ="获得项目简要信息")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('design:house:query')")
    public CommonResult<HouseSimInfoVO> getSimHouseInfo(@RequestParam("id") Long id) {

        return success(houseService.getSimHouseInfo(id));
    }


    @GetMapping("/getUserHouseRoles/{id}")
    @Operation(summary ="获取项目内所属角色列表")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('design:house:query')")
    public CommonResult<List<String>> getUserHouseRoles(@PathVariable Long id) {

        return success(houseUserRelService.getHouseRolesByHouseIdAndUserId(id, SecurityFrameworkUtils.getLoginUserId()));
    }


    @GetMapping("/getHouseTaskStatic")
    @Operation(summary ="统计所属项目内待处理任务 问题 数量")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('design:house:query')")
    public CommonResult<PageResult<HouseTaskStaticResVO>>  getHouseTaskStatic(@Valid HousePageReqVO pageVO) {

        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        HouseUserRelDO houseUserRelDO = new HouseUserRelDO();
        houseUserRelDO.setUserId(loginUser.getId());
        // 少一个我参与的
        houseUserRelDO.setStatus(UserRelStatusCdEnum.USER_REL_STATUS_CD_1.getCode().toString());
        List<HouseUserRelDO> userIds = houseUserRelService.getHouseUserRelList(houseUserRelDO);
        Set<Long> houseIds = userIds.stream().map(userRelDO -> userRelDO.getHouseId()).collect(Collectors.toSet());


        // 平台管理员跳过 权限控制
        if(CollUtil.isEmpty(houseIds)){
            return success(new PageResult<>(new ArrayList<>(), 0L));
        }else{
            pageVO.setIds(houseIds);
        }
        if(StrUtil.isEmpty(pageVO.getStatus())){
            pageVO.setStatus("1");
        }


        PageResult<HouseDO> pageResult = houseService.getHousePage(pageVO);

        // 项目id集合
        Set<Long> houseIdList = new HashSet<>(convertList(pageResult.getList(), HouseDO::getId));
        // 查询本人在每个项目的待办数
        Map<Long, FlowTaskCountDO> taskCountMap = flowTaskService.getTaskCountMap(houseIdList);
        // 查询本人在每个项目的采购任务关联数量
        Map<Long, FlowCountDO>   flowCountMap = flowService.getFlowCountMap(houseIdList);
        // 查询本人在每个项目的待处理问题数
        Map<Long, ProblemCountDO> problemCountMap = problemService.getProblemCountMap(houseIdList);
        // 查询本人 关联的采购任务数

        // 拼接结果返回
        List<HouseTaskStaticResVO> houseTaskStaticResVO = new ArrayList<>(pageResult.getList().size());
        pageResult.getList().forEach(house -> {
            HouseTaskStaticResVO respVO = HouseConvert.INSTANCE.convertTaskStatic(house);
            boolean taskFlg = taskCountMap.containsKey(house.getId());
            boolean problemFlg = problemCountMap.containsKey(house.getId());

            boolean purchaseFlg = flowCountMap.containsKey(house.getId());
            respVO.setPurchaseCount(purchaseFlg?flowCountMap.get(house.getId()).getTaskCount():0);
            respVO.setTaskCount(taskFlg?taskCountMap.get(house.getId()).getTaskCount():0);
            respVO.setProblemCount(problemFlg?problemCountMap.get(house.getId()).getProblemCount():0);
            houseTaskStaticResVO.add(respVO);

        });

        return success(new PageResult<>(houseTaskStaticResVO, pageResult.getTotal()));

    }

    @GetMapping("/getHousePicList/{id}")
    @Operation(summary ="获取项目内平面图和效果图")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('design:house:query')")
    public CommonResult<List<PicDO>> getHousePicList(@PathVariable Long id) {

        return success(houseService.getPicDataList(id,Arrays.asList(PicSourceTypeEnum.PIC_SOURCE_TYPE_ENUM_007.getCode(),
                PicSourceTypeEnum.PIC_SOURCE_TYPE_ENUM_008.getCode())) );
    }



}
